﻿using Aliyun.Acs.Core;
using Aliyun.Acs.Core.Exceptions;
using Aliyun.Acs.Core.Profile;
using Aliyun.Acs.Dysmsapi.Model.V20170525;
using System;
using System.Collections.Generic;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;

namespace PageAdmin.Utils
{
    /// <summary>
    /// 短信发送类，采用阿里云的接口
    /// </summary>
    public class SmsHelper
    {
        /// <summary>
        /// 短信发送,注:paramJsonString长度有限制，超过就报错。
        /// </summary>
        /// <param name="setting">AliYunSmsSetting设置类</param>
        /// <param name="mobiles">多个手机号多个用半角逗号隔开，单次发送数量不能超过100。</param>
        /// <param name="templateCode">模板编号</param>
        /// <param name="paramJsonString">传递的json字符串</param>
        /// <returns></returns>
        public static TipsInfo Send(AliYunSmsSetting setting,string mobiles, string templateCode,string paramJsonString)
        {
            TipsInfo tipsInfo = new TipsInfo()
            {
                State = 0,
                Msg = ""
            };
            if (string.IsNullOrEmpty(mobiles))
            {
                tipsInfo.Msg= "mobiles为空！";
                return tipsInfo;
            }
            if (string.IsNullOrEmpty(templateCode))
            {
                tipsInfo.Msg = "templateCode为空！";
                return tipsInfo;
            }
            if (string.IsNullOrEmpty(paramJsonString))
            {
                paramJsonString="{}";
            }
            paramJsonString = paramJsonString.Trim();
            if (paramJsonString.IndexOf("{")!=0 || paramJsonString.IndexOf("}")!= paramJsonString.Length-1)
            {
                tipsInfo.Msg = "paramJsonString参数必须为Json格式字符串";
                return tipsInfo;
            }

            String product = "Dysmsapi";//短信API产品名称（短信产品名固定，无需修改）
            String domain = "dysmsapi.aliyuncs.com";//短信API产品域名（接口地址固定，无需修改）
            String accessKeyId = setting.AccessKeyId;//你的accessKeyId，参考本文档步骤2
            String accessKeySecret = setting.AccessKeySecret;//你的accessKeySecret，参考本文档步骤2
            string signName = setting.SignName;
            if(string.IsNullOrEmpty(accessKeyId) || string.IsNullOrEmpty(accessKeySecret) || string.IsNullOrEmpty(signName))
            {
                tipsInfo.Msg = "accessKeyId,accessKeySecret和signName必须设置";
                return tipsInfo;
            }

            IClientProfile profile = DefaultProfile.GetProfile("cn-hangzhou", accessKeyId, accessKeySecret);
            //IAcsClient client = new DefaultAcsClient(profile);
            // SingleSendSmsRequest request = new SingleSendSmsRequest();
            //初始化ascClient,暂时不支持多region（请勿修改）
            DefaultProfile.AddEndpoint("cn-hangzhou", "cn-hangzhou", product, domain);
            IAcsClient acsClient = new DefaultAcsClient(profile);
            SendSmsRequest request = new SendSmsRequest();
            try
            {
                //必填:待发送手机号。支持以逗号分隔的形式进行批量调用，批量上限为1000个手机号码,批量调用相对于单条调用及时性稍有延迟,验证码类型的短信推荐使用单条调用的方式
                request.PhoneNumbers = mobiles;
                //必填:短信签名-可在短信控制台中找到
                request.SignName = signName;
                //必填:短信模板-可在短信控制台中找到
                request.TemplateCode = templateCode;
                //可选:模板中的变量替换JSON串,如模板内容为"亲爱的${name},您的验证码为${code}"时,此处的值为
                request.TemplateParam = paramJsonString;
                //可选:outId为提供给业务方扩展字段,最终在短信回执消息中将此值带回给调用者
                request.OutId = "";
                //请求失败这里会抛ClientException异常
                SendSmsResponse sendSmsResponse = acsClient.GetAcsResponse(request);
                System.Console.WriteLine(sendSmsResponse.Message);
                if(sendSmsResponse.Code.Equals("ok",StringComparison.OrdinalIgnoreCase))
                {
                    tipsInfo.Msg = "success";
                    tipsInfo.State = 1;
                }
                else
                {
                    tipsInfo.Msg = sendSmsResponse.Code+":"+ sendSmsResponse.Message;
                    tipsInfo.State =0;
                }
            }
            catch (ServerException e)
            {
                tipsInfo.Msg = e.Message;
            }
            catch (ClientException e)
            {
                tipsInfo.Msg = e.Message;
            }

            return tipsInfo;
        }

        /// <summary>
        /// 短信批量发送
        /// </summary>
        /// <param name="setting">AliYunSmsSetting设置类</param>
        /// <param name="mobileList">多个手机号码</param>
        /// <param name="templateCode">模板编号</param>
        /// <param name="paramList">模板内容变量</param>
        /// <returns></returns>

        public static TipsInfo Send(AliYunSmsSetting setting, List<string> mobileList, string templateCode,List<Dictionary<string,string>> paramList)
        {
            TipsInfo tipsInfo = new TipsInfo();
            String product = "Dysmsapi";//短信API产品名称（短信产品名固定，无需修改）
            String domain = "dysmsapi.aliyuncs.com";//短信API产品域名（接口地址固定，无需修改）
            String accessKeyId = setting.AccessKeyId;//你的accessKeyId，参考本文档步骤2
            String accessKeySecret = setting.AccessKeySecret;//你的accessKeySecret，参考本文档步骤2
            string signName = setting.SignName;
            if (string.IsNullOrEmpty(accessKeyId) || string.IsNullOrEmpty(accessKeySecret) || string.IsNullOrEmpty(signName))
            {
                tipsInfo.State = 0;
                tipsInfo.Msg = "accessKeyId,accessKeySecret和signName必须设置";
                return tipsInfo;
            }
            if (mobileList.Count==0)
            {
                tipsInfo.State = 0;
                tipsInfo.Msg = "mobiles为空！";
                return tipsInfo;
            }
            if (string.IsNullOrEmpty(templateCode))
            {
                tipsInfo.State = 0;
                tipsInfo.Msg = "templateCode为空！";
                return tipsInfo;
            }
            if (paramList.Count == 0)
            {
                tipsInfo.State = 0;
                tipsInfo.Msg = "paramList为空！";
                return tipsInfo;
            }
            IClientProfile profile = DefaultProfile.GetProfile("cn-hangzhou", accessKeyId, accessKeySecret);
            DefaultProfile.AddEndpoint("cn-hangzhou", "cn-hangzhou", product, domain);
            IAcsClient acsClient = new DefaultAcsClient(profile);
            SendBatchSmsRequest request = new SendBatchSmsRequest();
            SendBatchSmsResponse response = null;
            List<string> signNameList = new List<string>();
            foreach (var ss in mobileList)
            {
                signNameList.Add(signName);
            }
            try
            {
                //必填:待发送手机号。支持JSON格式的批量调用，批量上限为100个手机号码,批量调用相对于单条调用及时性稍有延迟,验证码类型的短信推荐使用单条调用的方式
                request.PhoneNumberJson = JsonHelper.JsonParse(mobileList);
                //必填:短信签名-支持不同的号码发送不同的短信签名
                request.SignNameJson = JsonHelper.JsonParse(signNameList);
                //必填:短信模板-可在短信控制台中找到
                request.TemplateCode = templateCode;
                //必填:模板中的变量替换JSON串,如模板内容为"亲爱的${name},您的验证码为${code}"时,此处的值为
                //友情提示:如果JSON中需要带换行符,请参照标准的JSON协议对换行符的要求,比如短信内容中包含\r\n的情况在JSON中需要表示成\\r\\n,否则会导致JSON在服务端解析失败
                request.TemplateParamJson = JsonHelper.JsonParse(paramList);
                //可选-上行短信扩展码(扩展码字段控制在7位或以下，无特殊需求用户请忽略此字段)
                //request.SmsUpExtendCodeJson = "[\"90997\",\"90998\"]";
                //请求失败这里会抛ClientException异常
                response = acsClient.GetAcsResponse(request);
                if (response.Code.Equals("ok", StringComparison.OrdinalIgnoreCase))
                {
                    tipsInfo.Msg = "success";
                    tipsInfo.State = 1;
                }
                else
                {
                    tipsInfo.Msg = response.Code + ":" + response.Message;
                    tipsInfo.State = 0;
                }
            }
            catch (ServerException e)
            {
                tipsInfo.State = 0;
                tipsInfo.Msg = e.Message;
                tipsInfo.Data = e.ErrorCode;
            }
            catch (ClientException e)
            {
                tipsInfo.State = 0;
                tipsInfo.Msg = e.Message;
                tipsInfo.Data = e.ErrorCode;
            }
            return tipsInfo;
        }

        private static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
        {
            return true;
        }
    }
}